/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clientside;

import client.gui.MainView;
import java.io.*;
import java.net.*;
import client.network.*;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.UIManager;

/**
 *
 * @author TrungHieu
 */
public class ClientSide {
   	private static String machine = "localhost";
	private static Integer portControl = 1999;
	private static Socket clientSocket = null;

	private static BufferedReader infromScreen = null;
	private static BufferedReader in = null;
	private static PrintStream out = null;
    private static Boolean flag = false;

	public static void  newChat(){
		try{
			out = new PrintStream(new DataOutputStream(clientSocket.getOutputStream()));
		 	in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            infromScreen = new BufferedReader(new InputStreamReader(System.in));
		}
		catch(IOException e){}
	}
    public static void closeConnection(){
			try {
				out.close();
				in.close();
				clientSocket.close();
			}
			catch (IOException e){}

	}

    public static void setFlag(Boolean f){
        flag = f;
    }

	public static void main( String[] args ) {

         try {
			 clientSocket = new Socket(machine,portControl);
             newChat();
             System.out.println("Client start! \nEnter username: ");
             String userName = infromScreen.readLine();
             System.out.println(userName);
             out.println(userName);
             (new Thread(new ClientNetwork.ClientTask(in, out,clientSocket))).start();
             while(!flag);
             closeConnection();

        } catch (IOException e) {
	            System.err.println("Could not listen on port:" + portControl);
//	            System.exit(-1);
	     }
		try {
			UIManager.setLookAndFeel( "com.seaglasslookandfeel.SeaGlassLookAndFeel" );
//			UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" );
			Toolkit tk = Toolkit.getDefaultToolkit();
			MainView mainview = new MainView();
			mainview.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
			mainview.setSize( tk.getScreenSize().width - 10, tk.getScreenSize().height - 50 );
			mainview.setLocationRelativeTo( null );
			mainview.setVisible( true );
		}
		catch ( Exception e ) {
			e.printStackTrace();
		}
	}
}
